﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using RedeSocial.DataAccess;
using System.Collections.ObjectModel;
using RedeSocial.ViewModels.Interfaces;
using RedeSocial.ViewModels.Enums;

namespace RedeSocial.ViewModels
{

	public class LoginViewModel : BaseViewModel, ILogin
	{
		#region fields...
		private string _email;
		private string _password;

		#endregion
		#region properties...
		public string Email
		{
			get { return _email; }
			set
			{
				_email = value;
				NotifyPropertyChange("Email");
			}
		}
		public string Password
		{
			get { return _password; }
			set
			{
				_password = value;
				NotifyPropertyChange("Password");
			}
		}
		#endregion
		#region methods...
		public Session Login()
		{
			Session session = null;
			string encPwd = Security.Encrypt(Password);
			using (var dataContext = new RedeSocialEntities())
			{
				User user = dataContext.Users.Include("Country").Include("File").Where(u => u.UserState == (int)UserState.Enabled &&
						u.Email.Equals(Email, StringComparison.CurrentCultureIgnoreCase) &&
						u.Password.Equals(encPwd, StringComparison.CurrentCultureIgnoreCase)).FirstOrDefault();
				if (user != null)
				{
					session = dataContext.Sessions.Where(s => s.User.Id == user.Id).FirstOrDefault();
					if (session == null)
						session = new Session() { ConnectedOn = DateTime.Now, LastAccess = DateTime.Now, User = user };
					dataContext.Sessions.Add(session);
					dataContext.SaveChanges();
				}
			}
			return session;
		}
		#endregion
	}
}
